package com.splant.android.smart.UILevel;

/**
 * Created by Administrator on 2015/12/28.
 */

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.splant.android.smart.CommunicationLevel.Bluetooth.BluetoothClientManager;
import com.splant.android.R;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Switchs.SlideSwitch;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class System_Bluetooth_Main_Activity extends Activity implements View.OnClickListener {
    private SlideSwitch bluetoothSwitch;
    private Button search_button;
    private ImageView img_goBack;

    private static final int REQUEST_DISCOVERY = 0x1;
    private ListView comm_listview_devicelist;
    private List<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();

    private BluetoothClientManager bluetoothClientManager;
    private System_Bluetooth_DeviceList_Adapter systemBluetooth_Adapter_BondeDeviceList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.system_bluetooth_main_activity);

        bluetoothSwitch = (SlideSwitch) this.findViewById(R.id.bluetoothSwitch);
        search_button = (Button) this.findViewById(R.id.search_button);
        comm_listview_devicelist = (ListView) this.findViewById(R.id.comm_listview_devicelist);
        img_goBack = (ImageView) findViewById(R.id.img_goBack);

//        CommHandleManager commHandleManager = CommHandleManager.getInstance(this, null);
//
//        bluetoothClientManager = commHandleManager.getBluetoothClientManager();

        if (bluetoothClientManager != null) {
            if (bluetoothClientManager.isEnabled())
                bluetoothSwitch.setStatus(true);

            getBondedBluetoothDevices();

            systemBluetooth_Adapter_BondeDeviceList = new System_Bluetooth_DeviceList_Adapter(this, bluetoothDeviceList);
            comm_listview_devicelist.setAdapter(systemBluetooth_Adapter_BondeDeviceList);

            bluetoothSwitch.setOnSwitchChangedListener(bluetoothSwitch_Chick);

            search_button.setOnClickListener(search_button_Chick);

            comm_listview_devicelist.setOnItemClickListener(comm_listview_devicelist_itemchick);
        }

        img_goBack.setOnClickListener(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BLUETOOTH_CONNECTDEVICE_SUCCESS);
        intentFilter.addAction(BLUETOOTH_CONNECTDEVICE_FAILURE);
        intentFilter.addAction(CONNECTDEVICE_GETVERSION_SUCCESS);
        intentFilter.addAction(CONNECTDEVICE_GETVERSION_FAILURE);

        registerReceiver(connectDeviceBroadcastReceiver, intentFilter);

    }
    public static final String BLUETOOTH_CONNECTDEVICE_SUCCESS="bluetooth.connectdevice.success";
    public static final String BLUETOOTH_CONNECTDEVICE_FAILURE="bluetooth.connectdevice.failure";
    public static final String CONNECTDEVICE_GETVERSION_SUCCESS="connectdevice.getversion.success";
    public static final String CONNECTDEVICE_GETVERSION_FAILURE="connectdevice.getversion.failure";


    private void getBondedBluetoothDevices() {
        bluetoothDeviceList.clear();
        Set<BluetoothDevice> bluetoothDevices = bluetoothClientManager.getBondedDevices();

        for (BluetoothDevice b : bluetoothDevices)
            bluetoothDeviceList.add(b);
    }

    private static LoadingDialog loadingDialog;
    private AdapterView.OnItemClickListener comm_listview_devicelist_itemchick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            boolean isContact = false;
            BluetoothDevice bluetoothDevice = null;
            if (bluetoothClientManager.getConnectState() != BluetoothClientManager.STATE_CONNECTING) {
                bluetoothDevice = bluetoothDeviceList.get(i);
                isContact = true;
            } else
                bluetoothDevice = bluetoothClientManager.getDevice();

            loadingDialog = LoadingDialog.createDialog(System_Bluetooth_Main_Activity.this);
            loadingDialog.setMessage(getString(R.string.system_bluetooth_connect_title) +" "+ bluetoothDevice.getName() + " ……");

            if (!loadingDialog.isShowing())
                loadingDialog.show();

            if (isContact) {
                bluetoothClientManager.connect(bluetoothDevice);
            }
        }
    };
    private SlideSwitch.OnSwitchChangedListener bluetoothSwitch_Chick = new SlideSwitch.OnSwitchChangedListener() {
        @Override
        public void onSwitchChanged(SlideSwitch obj, int status) {
            if (status == SlideSwitch.SWITCH_ON)
                bluetoothClientManager.openBluetooth();
            else if (status == SlideSwitch.SWITCH_OFF)
                bluetoothClientManager.closeBluetooth();
        }
    };
    private View.OnClickListener search_button_Chick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(System_Bluetooth_Main_Activity.this, System_Bluetooth_Discovery_Activity.class);
            startActivityForResult(intent, REQUEST_DISCOVERY);
            overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);

        }
    };

    /* 选择了服务器之后进行连接 */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode != REQUEST_DISCOVERY) {
            return;
        }
        if (resultCode != RESULT_OK) {
            return;
        }
        if (!bluetoothClientManager.isEnabled()) {
            Toast.makeText(System_Bluetooth_Main_Activity.this, getString(R.string.system_bluetooth_open_txt), Toast.LENGTH_SHORT).show();
            return;
        }

        getBondedBluetoothDevices();

        BluetoothDevice d = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        Iterator<BluetoothDevice> bluetoothDeviceIterator = bluetoothDeviceList.iterator();

        while (bluetoothDeviceIterator.hasNext()) {
            BluetoothDevice device = bluetoothDeviceIterator.next();
            if (device.equals(d)) {
                bluetoothDeviceIterator.remove();
            }
        }

        bluetoothDeviceList.add(0, d);

        systemBluetooth_Adapter_BondeDeviceList.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(connectDeviceBroadcastReceiver);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.img_goBack:
                finish();
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
        }
    }
    private BroadcastReceiver connectDeviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(BLUETOOTH_CONNECTDEVICE_SUCCESS)) {
                showInfoPrompt(getString(R.string.system_bluetooth_connect_success_txt));
            }
            else if (intent.getAction().equals(BLUETOOTH_CONNECTDEVICE_FAILURE))
            {
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.cancel();

                showInfoPrompt(getString(R.string.system_bluetooth_connect_failure_txt));
            }
            else if (intent.getAction().equals(CONNECTDEVICE_GETVERSION_SUCCESS))
            {
                showInfoPrompt(getString(R.string.system_device_connect_success_txt));
                finish();
            }
            else if (intent.getAction().equals(CONNECTDEVICE_GETVERSION_FAILURE))
            {
                if (loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.cancel();
                showInfoPrompt(getString(R.string.system_device_connect_failure_txt));
            }

        }
    };
    private void showInfoPrompt(String infoStr) {
        Toast.makeText(System_Bluetooth_Main_Activity.this, infoStr, Toast.LENGTH_SHORT).show();
    }

}
